package com.xsz.pda.ui

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.github.kittinunf.fuel.httpPost
import com.xsz.pda.App
import com.xsz.pda.Config
import com.xsz.pda.R
import com.xsz.pda.api.beans.ApiTicketFace
import com.xsz.pda.data.db.LocalDB
import com.xsz.pda.device.nfc.NFCReader

class DeleteFaceActivity : AppCompatActivity() {

    private lateinit var rfid: TextView
    private lateinit var nfcReader: NFCReader
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_delete_face)
        rfid = findViewById(R.id.nowRfid)
        nfcReader = NFCReader(this)
        nfcReader.setOnReadListener {
            runOnUiThread {
                rfid.text  = it
            }
            ThreadUtils.executeByIo(object :
                ThreadUtils.Task<Boolean>() {
                override fun doInBackground(): Boolean {
                    delFace(it)
                    return true
                }
                override fun onSuccess(result: Boolean) {}
                override fun onCancel() {}
                override fun onFail(t: Throwable?) {}
            })
        }
    }

    override fun onResume() {
        super.onResume()
        nfcReader.touch()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (!App.checkIdCard) {
            intent?.let { nfcReader.parse(it) }
        }

    }
    private val db = LocalDB.get(Utils.getApp())
    private val ticketDao = db.ticketDao()
    private fun delFace(m1: String) {
        val ti = ticketDao.findByM1(m1 = m1)
        if (ti != null) {
            val ticketId = ti.ticket.id
            "http://${Config.ip}:8080/checker/api/client/delFace?ticketId=$ticketId"
                .httpPost()
                .responseString {_,_,r->
                    r.fold({
                        ToastUtils.showShort(it)
                    },{
                        ToastUtils.showShort(it.exception.message)
                    })
                }
        } else {
            ToastUtils.showShort("未查到票，请先同步本项目数据")
        }

    }

}